package algorithms.evictpolicy;


import java.util.Arrays;

public class LRU_K<K extends Comparable<K>, V> extends LRU<K, V> {

    private static final int DEFAULT_THRESHOLD = 2;
    private int threshold;

    private LRU<K, Integer> history;

    public LRU_K(int size, int threshold, int historySize) {
        super(size);
        this.threshold = threshold;
        history = new LRU<>(historySize);
    }

    public LRU_K(int size, int historySize) {
        this(size, DEFAULT_THRESHOLD, historySize);
    }

    public LRU_K(int size) {
        this(size, size);
    }


    @Override
    public void put(K k, V v) {
        if (super.exists(k)) super.put(k, v);
        Integer count = history.get(k);
        count = count == null ? 1 : count + 1;
        if (count == threshold) {
            history.remove(k);
            super.put(k, v);
            sortQueue();
        } else history.put(k, count);
    }

    @Override
    public void remove(K k) {
        if (super.exists(k)) super.remove(k);
        else history.remove(k);
    }

    private void sortQueue() {
        Arrays.sort(queue);
    }

    public static void main(String[] args) {
        LRU_K<String, String> cache = new LRU_K<>(5);
        cache.put("Q", "B");
        cache.put("B", "B");
        cache.put("B", "B");
        cache.put("C", "C");
        cache.put("D", "D");
        cache.put("E", "E");
        cache.put("F", "F");
        cache.put("G", "G");
        cache.put("Q", "Q");
        cache.put("G", "G");
        System.out.println(cache.get("G"));
    }
}
